﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace BusinessPlatform.Core.BusinessObject
{
    internal class BusinessObjectFactory : IBusinessObjectFactory
    {
        public object CreateInstance(Type type)
        {
            if (type.IsClass && type.IsAbstract == false)
                return Activator.CreateInstance(type);
            else
            {
                if (type.IsInterface)
                {
                    foreach (var ExType in type.Assembly.GetExportedTypes())
                    {
                        foreach (var intface in ExType.GetInterfaces())
                        {
                            if (intface.FullName == type.FullName)
                            {
                                return Activator.CreateInstance(ExType);
                            }
                        }
                    }

                }
            }
            return null;
        }

        public T CreateInstance<T>() where T : IBusinessObjectBase
        {
            Type type = typeof(T);
            if (type.IsClass && type.IsAbstract == false)
                return Activator.CreateInstance<T>();
            else
            {
                if (type.IsInterface)
                {
                    foreach (var ExType in type.Assembly.GetExportedTypes())
                    {
                        foreach (var intface in ExType.GetInterfaces())
                        {
                            if (intface.FullName == type.FullName)
                            {
                                return (T)Activator.CreateInstance(ExType);
                            }
                        }
                    }

                }
            }
            return default(T);
        }
    }
}
